﻿#include "postchange.h"
#include "ui_postchange.h"
#include <QDebug>
#include <QMessageBox>
#include <QSqlQuery>
#include <QFileDialog>
#include <QFile>
#include <QDomDocument> //文件
#include <QDomProcessingInstruction> //格式头部
#include <QDomElement>  //元素
#include <QTextStream> //文件流
#include <QPrinter>
#include <QTextDocument>
#include <QTextBlock>
#include <QDesktopServices>
#include <QUrl>
#define cout qDebug() << "[" << __FILE__ << ":" << __LINE__ << "]"

PostChange::PostChange(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::PostChange)
{
    ui->setupUi(this);

    initForm(); //锁定编辑

    initTableWidget(); //初始化tableWidget

    showCadreFileData();
    //锁定编辑
    connect(ui->buttonLock,SIGNAL(clicked()),this,SLOT(lockEdit()));
    //打印
    //connect(ui->buttonPrint,SIGNAL(clicked()),this,SLOT(sendPrintSlot()));
    //职务变动
    postchangeinfomanage = new PostChangeInfoMange();
    connect(ui->buttonCM,SIGNAL(clicked()),postchangeinfomanage,SLOT(show()));

}

PostChange::~PostChange()
{
    delete ui;
}

//初始化
void PostChange::initForm()
{
    ui->lineEdit->setEnabled(false);
    ui->buttonFind->setEnabled(false);
    ui->buttonEdit->setEnabled(false);
    ui->buttonPrint->setEnabled(false);
    ui->buttonInOut->setEnabled(false);
    ui->buttonAdd->setEnabled(false);
    ui->buttonDel->setEnabled(false);
    ui->buttonUp->setEnabled(false);
    ui->buttonDown->setEnabled(false);
    ui->buttonInsert->setEnabled(false);
    ui->buttonCM->setEnabled(false);
}

//使能按钮
void PostChange::enableForm()
{
    ui->lineEdit->setEnabled(true);
    ui->buttonFind->setEnabled(true);
    ui->buttonEdit->setEnabled(true);
    ui->buttonPrint->setEnabled(true);
    ui->buttonInOut->setEnabled(true);
    ui->buttonAdd->setEnabled(true);
    ui->buttonDel->setEnabled(true);
    ui->buttonUp->setEnabled(true);
    ui->buttonDown->setEnabled(true);
    ui->buttonInsert->setEnabled(true);
    ui->buttonCM->setEnabled(true);
}

//初始化tableWidget
void PostChange::initTableWidget()
{
    ui->tableWidget_da->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->tableWidget_da->setSelectionBehavior(QAbstractItemView::SelectRows);  //整行选中的方式
    ui->tableWidget_da->setSelectionMode(QAbstractItemView::SingleSelection);  //设置为可以选中单个
    ui->tableWidget_da->horizontalHeader()->setStyleSheet("QHeaderView::section{background:skyblue;}"); //设置表头的背景色
    ui->tableWidget_da->setStyleSheet("selection-background-color:rgb(173,216,230);"); //设置选中行的背景色

    ui->tableWidget_rm->verticalHeader()->setVisible(false); //不显示左边序号
    ui->tableWidget_rm->horizontalHeader()->setFixedHeight(30); //表头高
    ui->tableWidget_rm->setSelectionBehavior(QAbstractItemView::SelectRows);  //整行选中的方式
    ui->tableWidget_rm->setSelectionMode(QAbstractItemView::SingleSelection);  //设置为可以选中单个
    ui->tableWidget_rm->horizontalHeader()->setStyleSheet("QHeaderView::section{background:skyblue;}"); //设置表头的背景色
    ui->tableWidget_rm->setStyleSheet("selection-background-color:rgb(173,216,230);"); //设置选中行的背景色

}

//锁定编辑
void PostChange::lockEdit()
{
    QString str = ui->buttonLock->text();

    if(str == "编辑(F1)")
    {
        ui->buttonLock->setText("锁定(F1)");
        enableForm();
    }
    else
    {
        ui->buttonLock->setText("编辑(F1)");
        initForm();
    }
}

//发送信号，调用目录打印操作界面
void PostChange::sendPrintSlot()
{
    emit printSignal();
}

//查询显示干部档案信息
void PostChange::showCadreFileData()
{
    ui->tableWidget_da->setRowCount(0);
    QSqlQuery query;
    query.exec("select CadreName,IDNum,UnitID,Birth,NativePlace,Sex from CadreInfo");
    while(query.next()) //一行一行遍历
    {
        int rowc = ui->tableWidget_da->rowCount();//获取行数
        ui->tableWidget_da->insertRow(rowc);
        //干部名称/性别/证件号码
        ui->tableWidget_da->setItem(rowc,0,new QTableWidgetItem(query.value(0).toString()));
        if(query.value(5).toString()== "1")
            ui->tableWidget_da->setItem(rowc,1,new QTableWidgetItem("男"));
        if(query.value(5).toString()== "0")
            ui->tableWidget_da->setItem(rowc,1,new QTableWidgetItem("女"));
        ui->tableWidget_da->setItem(rowc,2,new QTableWidgetItem(query.value(1).toString()));
        //单位
        QString sqlUnit = QString("select unitname from unit where unitid = '%1'").arg(query.value(2).toString());
        QSqlQuery queryUnit;
        queryUnit.exec(sqlUnit);
        while(queryUnit.next()) //一行一行遍历
        {
            ui->tableWidget_da->setItem(rowc,5,new QTableWidgetItem(queryUnit.value(0).toString()));
        }
        //转入转出时间
        QString sqlInTime = QString("select FileRecTime from FileReceive where IDNum = '%1'").arg(query.value(1).toString());
        QSqlQuery queryInTime;
        queryInTime.exec(sqlInTime);
        while(queryInTime.next()) //一行一行遍历
        {
            ui->tableWidget_da->setItem(rowc,3,new QTableWidgetItem(queryInTime.value(0).toString()));
        }
        QString sqlOutTime = QString("select FileOutTime from FileOut where IDNum = '%1'").arg(query.value(1).toString());
        QSqlQuery queryOutTime;
        queryOutTime.exec(sqlOutTime);
        while(queryOutTime.next()) //一行一行遍历
        {
            ui->tableWidget_da->setItem(rowc,4,new QTableWidgetItem(queryOutTime.value(0).toString()));
        }
        //现任职务
        QString sqlPost = QString("select PostName from Post where QualifyType = '0' and IDNum = '%1'").arg(query.value(1).toString());
        QSqlQuery queryPost;
        queryPost.exec(sqlPost);
        while(queryPost.next()) //一行一行遍历
        {
            ui->tableWidget_da->setItem(rowc,6,new QTableWidgetItem(queryPost.value(0).toString()));
        }
        //出生时间
        ui->tableWidget_da->setItem(rowc,7,new QTableWidgetItem(query.value(3).toString()));
        //籍贯
        QString sqlAdminArea = QString("select AdminArea from AdminAreaCode where AdminAreaID = '%1'").arg(query.value(4).toString());
        QSqlQuery queryAdminArea;
        queryAdminArea.exec(sqlAdminArea);
        while(queryAdminArea.next()) //一行一行遍历
        {
            ui->tableWidget_da->setItem(rowc,8,new QTableWidgetItem(queryAdminArea.value(0).toString()));
        }
        //档案信息
        QString sqlFile = QString("select FileNum,FileSite,RollNum,CopyNum,Remark from File where IDNum = '%1'").arg(query.value(1).toString());
        QSqlQuery queryFile;
        queryFile.exec(sqlFile);
        while(queryFile.next()) //一行一行遍历
        {
            for(int i = 9; i<14;i++)
            {
                ui->tableWidget_da->setItem(rowc,i,new QTableWidgetItem(queryFile.value(i-9).toString()));
            }
        }
    }
    int rows = ui->tableWidget_da->rowCount();
    QString newtext = QString(" 共: %1 条").arg(rows);
    ui->label_2->setText(newtext);
}

//交换两行记录数据
void PostChange::SwapTwoRow(int selectRow, int targetRow)
{
    QStringList selectRowLine, targetRowLine;//创建两个QStringList用于储存表格数据
    int colCount = ui->tableWidget_rm->columnCount();
    for (int i = 0; i < colCount; i++)
    {
        //获取文本，并添加进QStringLine
        selectRowLine.append(ui->tableWidget_rm->item(selectRow, i)->text());
        targetRowLine.append(ui->tableWidget_rm->item(targetRow, i)->text());
    }
    for (int i = 0; i < colCount; i++)
    {
        ui->tableWidget_rm->setItem(selectRow, i, new QTableWidgetItem(targetRowLine.at(i))); //设置文本
        ui->tableWidget_rm->setItem(targetRow, i, new QTableWidgetItem(selectRowLine.at(i)));
    }
}

//上移
void PostChange::on_buttonUp_clicked()
{
    int m_CurrentRow = ui->tableWidget_rm->currentRow();//获取当前行的Index
    if (m_CurrentRow != -1)//如果选中了数据，（未选择数据之前，返回值是-1）
    {
        if (m_CurrentRow != 0)//如果选定行不在第一行
        {
            SwapTwoRow(m_CurrentRow, m_CurrentRow - 1);
            ui->tableWidget_rm->setCurrentCell(m_CurrentRow - 1, QItemSelectionModel::Select);//移动过后继续选定该行
        }
    }
    else
    {
       if (ui->tableWidget_rm->rowCount() != 0)//如果有数据，但是currentRow=--1 说明没有选择数据,把焦点定位到第一行
       {
            QMessageBox::critical(this, tr("错误！"), tr("无法移动：未选择数据！"));
       }
       else
       {
            QMessageBox::critical(this, tr("错误！"), tr("无法移动：表格中没有数据！"));
       }
    }
}

//下移
void PostChange::on_buttonDown_clicked()
{
    int m_CurrentRow = ui->tableWidget_rm->currentRow();
    if (m_CurrentRow != -1)//如果选中了一行
    {
        if (m_CurrentRow != (ui->tableWidget_rm->rowCount() - 1))//如果不是最后一行
        {
            SwapTwoRow(m_CurrentRow, m_CurrentRow + 1);
            ui->tableWidget_rm->setCurrentCell(m_CurrentRow + 1, QItemSelectionModel::Select);//移动过后继续选定该行
        }

    }
    else
    {
        if (ui->tableWidget_rm->rowCount() != 0)//如果有数据，但是currentRow=--1 说明没有选择数据,把焦点定位到第一行
        {
            QMessageBox::critical(this, tr("错误！"), tr("无法移动：未选择数据！"));
        }
        else
        {
            QMessageBox::critical(this, tr("错误！"), tr("无法移动：表格中没有数据！"));
        }
    }
}

//界面上方区域查找干部
void PostChange::on_buttonFind_clicked()
{
    int rows = ui->tableWidget_da->rowCount();
    QString gbName = ui->lineEdit->text();
    int newrows=0;
    if ("" == gbName)
    {   //判断输入是否为空
        for (int i = 0; i < rows; i++)
        {
            ui->tableWidget_da->setRowHidden(i, false);//显示所有行
        }
    }
    else
    {
        QList <QTableWidgetItem *> item = ui->tableWidget_da->findItems(gbName, Qt::MatchContains);

        for (int i = 0; i < rows; i++)
        {
            ui->tableWidget_da->setRowHidden(i, true);//隐藏所有行
        }

        if (!item.isEmpty())
        {
            newrows = item.count();
            for (int i = 0; i < newrows; i++)
            {
                ui->tableWidget_da->setRowHidden(item.at(i)->row(),false);//item.at(i).row()输出行号

            }
        }
    }
    QString newtext = QString(" 共: %1 条").arg(newrows);
    ui->label_2->setText(newtext);
}

//导出xml文件
void PostChange::on_buttonInOut_clicked()
{
    int currentRow = ui->tableWidget_da->currentRow();
    if (currentRow != -1)//如果选中了一行
    {
        QString fileName = QFileDialog::getSaveFileName( this, "Save", "../", "*.xml" );

        if (QFileInfo(fileName).suffix().isEmpty())
        {
            fileName.append(".xml");
        }

        QFile file( fileName );
        /*if( true == file.exists() ) //如果存在不创建
        {
            cout << "文件已经存在";
            return;
        }
        else
        {*/ //不存在才创建
            //只写方式打开文件
            bool isOk = file.open(QIODevice::WriteOnly);
            if(true == isOk)//如果打开成功
            {
                //创建xml文档对象
                QDomDocument doc;
                //创建xml头部格式 <?xml version='1.0' encoding='utf-8'?>
                QDomProcessingInstruction ins;
                ins = doc.createProcessingInstruction("xml", "version=\'1.0\' encoding=\'utf-8\'");
                //追加元素
                doc.appendChild(ins);

                //根节点元素
                QDomElement root = doc.createElement("职务变动表");
                doc.appendChild(root);

                //创建干部信息子节点元素
                QDomElement gbEmt = doc.createElement("干部信息");
                //把节点追加到根节点上
                root.appendChild(gbEmt);

                //干部信息元素
                QDomElement cadreName = doc.createElement("姓名");
                QDomElement sex= doc.createElement("性别");
                QDomElement birth = doc.createElement("出生时间");
                QDomElement nativePlace = doc.createElement("籍贯");

                //QList<QTableWidgetItem*> items = ui->tableWidget_da->selectedItems();

                //QTableWidgetItem *item0 = items.at(0);

                //QString nameText = items.at(0)->text(); //获取内容
                QString nameText,sexText,birthText,jgText;
                if(ui->tableWidget_da->item(currentRow,0)!=NULL){
                    nameText = ui->tableWidget_da->item(currentRow,0)->text();
                }
                //qDebug()<<nameText;

                //QTableWidgetItem *item1 = items.at(1);
                if(ui->tableWidget_da->item(currentRow,1)!=NULL){
                    sexText = ui->tableWidget_da->item(currentRow,1)->text();
                }
                //qDebug()<<sexText;

                //QTableWidgetItem *item3 = items.at(3);
                if(ui->tableWidget_da->item(currentRow,7)!=NULL){
                    birthText = ui->tableWidget_da->item(currentRow,7)->text();
                }
                //qDebug()<<birthText;

                //QTableWidgetItem *item4 = items.at(4);
                if(ui->tableWidget_da->item(currentRow,8)!=NULL){
                    jgText = ui->tableWidget_da->item(currentRow,8)->text();
                }
                //qDebug()<<jgText;

                QDomText text;
                text = doc.createTextNode(nameText);
                cadreName.appendChild(text);

                text = doc.createTextNode(sexText);
                sex.appendChild(text);

                text = doc.createTextNode(birthText);
                birth.appendChild(text);

                text = doc.createTextNode(jgText);
                nativePlace.appendChild(text);

                gbEmt.appendChild(cadreName);
                gbEmt.appendChild(sex);
                gbEmt.appendChild(birth);
                gbEmt.appendChild(nativePlace);

                int rows_rm = ui->tableWidget_rm->rowCount();
                //int cols_rm = ui->tableWidget_rm->columnCount();

                for(int i=0;i<rows_rm;i++)
                {
                    //创建干部信息子节点元素
                    QDomElement rmEmt = doc.createElement("任免信息");

                    //把节点追加到根节点上
                    root.appendChild(rmEmt);

                    //任免信息元素
                    QDomElement postTime = doc.createElement("任职时间");
                    QDomElement noPostTime= doc.createElement("免职时间");
                    QDomElement unit = doc.createElement("单位");
                    QDomElement post = doc.createElement("职务");
                    QDomElement postNum= doc.createElement("任职文号");
                    QDomElement noPostNum = doc.createElement("免职文号");
                    QDomElement rank = doc.createElement("现任职级");

                    QDomText text;

                    QString ptText,nptText,uText,pText,pnText,npnText,rText;

                    if(ui->tableWidget_rm->item(i,0)){
                        ptText = ui->tableWidget_rm->item(i,0)->text();
                        text = doc.createTextNode(ptText);
                        postTime.appendChild(text);
                    }
                    if(ui->tableWidget_rm->item(i,1)){
                        nptText = ui->tableWidget_rm->item(i,1)->text();
                        text = doc.createTextNode(nptText);
                        noPostTime.appendChild(text);
                    }
                    if(ui->tableWidget_rm->item(i,2)){
                        uText = ui->tableWidget_rm->item(i,2)->text();
                        text = doc.createTextNode(uText);
                        unit.appendChild(text);
                    }
                    if(ui->tableWidget_rm->item(i,3)){
                        pText = ui->tableWidget_rm->item(i,3)->text();
                        text = doc.createTextNode(pText);
                        post.appendChild(text);
                    }
                    if(ui->tableWidget_rm->item(i,4)){
                        pnText = ui->tableWidget_rm->item(i,4)->text();
                        text = doc.createTextNode(pnText);
                        postNum.appendChild(text);
                    }
                    if(ui->tableWidget_rm->item(i,5)){
                        npnText = ui->tableWidget_rm->item(i,5)->text();
                        text = doc.createTextNode(npnText);
                        noPostNum.appendChild(text);
                    }
                    if(ui->tableWidget_rm->item(i,6)){
                        rText = ui->tableWidget_rm->item(i,6)->text();
                        text = doc.createTextNode(rText);
                        rank.appendChild(text);
                    }

                    rmEmt.appendChild(postTime);
                    rmEmt.appendChild(noPostTime);
                    rmEmt.appendChild(unit);
                    rmEmt.appendChild(post);
                    rmEmt.appendChild(postNum);
                    rmEmt.appendChild(noPostNum);
                    rmEmt.appendChild(rank);

                }
                //保存
                QTextStream stream(&file); //文本流关联文件
                doc.save(stream, 4); //4 缩进字符
                file.close(); //关闭文件

                QMessageBox::information(this,"提示","导出成功！");
             }

            else
            {
                cout << "WriteOnly error";
                return;
            }

        //}

    }
    else
    {
        if (ui->tableWidget_da->rowCount() != 0)//如果有数据，但是currentRow=--1 说明没有选择数据,把焦点定位到第一行
        {
            QMessageBox::critical(this, tr("错误！"), tr("无法移动：未选中干部！"));
        }
        else
        {
            QMessageBox::critical(this, tr("错误！"), tr("无法移动：表格中没有数据！"));
        }
    }
}

//档案编辑
void PostChange::on_buttonEdit_clicked()
{
    emit fileEdit();
}

//刷新当前界面档案信息
void PostChange::on_buttonRefresh_clicked()
{
    ui->tableWidget_da->setRowCount(0);
    showCadreFileData();
}

//形成html
QString PostChange::saveHtmlToPDF(QString fileName)
{
    QString html = "";
    html += "<html>";
    html += "<head>";
    html += "<title>"+fileName+"</title>";
    html += "<head>";
    html += "<body>";
    html += "<h1>职务变动信息</h1>";
    //html += "</table>";

    html += "<table width=\"100%\" border=\"1\" cellspacing=\"0\" cellpadding=\"0\" align=\"center\">";
        html += "<tr>";
            html += "<td align=\"center\" height=\"60\">------干部信息------</td>";
        html += "</tr>";
    html += "</table>";

    html += "<table width=\"100%\" border=\"1\" cellspacing=\"0\" cellpadding=\"0\" align=\"center\">";
    //QList<QTableWidgetItem*> items = ui->tableWidget_da->selectedItems();
    int currentRow = ui->tableWidget_da->currentRow();
    html += "<tr>";
        html += "<th>干部姓名</th>";
        html += "<th>性别</th>";
        html += "<th>出生时间</th>";
        html += "<th>籍贯</th>";
    html += "</tr>";
    html += "<tr>";
    if(ui->tableWidget_da->item(currentRow,0)!=NULL){
        html += "<th>"+ui->tableWidget_da->item(currentRow,0)->text()+"</th>";
    }
    if(ui->tableWidget_da->item(currentRow,1)!=NULL){
        html += "<th>"+ui->tableWidget_da->item(currentRow,1)->text()+"</th>";
    }
    if(ui->tableWidget_da->item(currentRow,7)!=NULL){
        html += "<th>"+ui->tableWidget_da->item(currentRow,7)->text()+"</th>";
    }
    if(ui->tableWidget_da->item(currentRow,8)!=NULL){
        html += "<th>"+ui->tableWidget_da->item(currentRow,8)->text()+"</th>";
    }
    html += "</tr>";
    html += "</table>";

    html += "<table width=\"100%\" border=\"1\" cellspacing=\"0\" cellpadding=\"0\" align=\"center\">";
    html += "<tr>";
        html += "<td align=\"center\" height=\"60\">------任免信息记录------</td>";
    html += "</tr>";
    html += "</table>";

    html += "<table width=\"100%\" border=\"1\" cellspacing=\"0\" cellpadding=\"0\" align=\"center\">";
    html += "<tr>";
        html += "<th>任职时间</th>";
        html += "<th>免职时间</th>";
        html += "<th>单位</th>";
        html += "<th>职务</th>";
        html += "<th>任职文号</th>";
        html += "<th>免职文号</th>";
        html += "<th>现任职级</th>";
    html += "</tr>";
    int rows_rm = ui->tableWidget_rm->rowCount();
    for(int i=0;i<rows_rm;i++)
    {
        html += "<tr>";
        if(ui->tableWidget_rm->item(i,0)!=NULL){
            html += "<th>"+ui->tableWidget_rm->item(i,0)->text()+"</th>";
        }
        if(ui->tableWidget_rm->item(i,1)!=NULL){
            html += "<th>"+ui->tableWidget_rm->item(i,1)->text()+"</th>";
        }
        if(ui->tableWidget_rm->item(i,2)!=NULL){
            html += "<th>"+ui->tableWidget_rm->item(i,2)->text()+"</th>";
        }
        if(ui->tableWidget_rm->item(i,3)!=NULL){
            html += "<th>"+ui->tableWidget_rm->item(i,3)->text()+"</th>";
        }
        if(ui->tableWidget_rm->item(i,4)!=NULL){
            html += "<th>"+ui->tableWidget_rm->item(i,4)->text()+"</th>";
        }
        if(ui->tableWidget_rm->item(i,5)!=NULL){
            html += "<th>"+ui->tableWidget_rm->item(i,5)->text()+"</th>";
        }
        if(ui->tableWidget_rm->item(i,6)!=NULL){
            html += "<th>"+ui->tableWidget_rm->item(i,6)->text()+"</th>";
        }
        html += "</tr>";
    }
    html += "</table>";

    html += "</body>";
    html += "</html>";
    return html;

}

//打印-形成pdf并打开
void PostChange::on_buttonPrint_clicked()
{
    int currentRow = ui->tableWidget_da->currentRow();
    if (currentRow != -1)//如果选中了一行
    {
        QString fileName = QFileDialog::getSaveFileName( this, "导出PDF文件", "../", "*.pdf" );

        if (!fileName.isEmpty())
        {
            // 如果文件后缀为空，则默认使用.pdf
            if (QFileInfo(fileName).suffix().isEmpty())
            {
                fileName.append(".pdf");
            }

            QPrinter *printer = new QPrinter(QPrinter::ScreenResolution);
            // 指定输出格式为pdf
            printer->setPageSize(QPrinter::A4);
            printer->setOutputFormat(QPrinter::PdfFormat);
            printer->setOutputFileName(fileName);

            QTextDocument document;
            document.setHtml(saveHtmlToPDF(fileName));
            document.print(printer);
            document.end();

            QString strPdf = fileName;
            //qDebug()<<strPdf;
            QDesktopServices::openUrl(QUrl::fromLocalFile(strPdf));
        }
     }
    else
    {
        QMessageBox::information(this,"提示信息","未选择打印条目行!");
    }
}

//插入数据至数据库(职务表)
void PostChange::on_buttonInsert_clicked()
{
    int daCurrentRow = ui->tableWidget_da->currentRow();
    if (daCurrentRow != -1)//当前选择行,数据插入表
    {
        QMessageBox::StandardButton result;
        result = QMessageBox::question(this,"确认消息框","确定信息正确并插入记录？",QMessageBox::Yes|QMessageBox::No);
        if(result==QMessageBox::Yes)
        {
            int rmCurrentRow = ui->tableWidget_rm->currentRow();
            if (rmCurrentRow != -1)//当前选择行,数据插入表
            {
                QString postTime = "null";
                QString postNum = "null";
                QString postType = "null";
                QString postName = "null";
                QString unitId = "null";
                QString rankId = "null";

                //职务
                postName = ui->tableWidget_rm->item(rmCurrentRow,3)->text();

                //证件号码
                int daCurrentRow = ui->tableWidget_da->currentRow();
                QString idNum = ui->tableWidget_da->item(daCurrentRow,2)->text();

                //任职
                if(ui->tableWidget_rm->item(rmCurrentRow,0)->text() != "" and ui->tableWidget_rm->item(rmCurrentRow,4)->text() !="")
                {
                    postTime = ui->tableWidget_rm->item(rmCurrentRow,0)->text();
                    postNum = ui->tableWidget_rm->item(rmCurrentRow,4)->text();
                    postType = "0";
                }
                //免职
                if(ui->tableWidget_rm->item(rmCurrentRow,1)->text() != "" and ui->tableWidget_rm->item(rmCurrentRow,5)->text() != "")
                {
                    postTime = ui->tableWidget_rm->item(rmCurrentRow,1)->text();
                    postNum = ui->tableWidget_rm->item(rmCurrentRow,5)->text();
                    postType = "3";
                }

                //单位
                if(ui->tableWidget_rm->item(rmCurrentRow,2)->text()!="")
                {
                    QString sqlUnit = QString("select unitid from unit where unitname = '%1'").arg(ui->tableWidget_rm->item(rmCurrentRow,2)->text());
                    QSqlQuery queryUnit;
                    queryUnit.exec(sqlUnit);
                    if(queryUnit.next()) //一行一行遍历
                    {
                        unitId = queryUnit.value(0).toString();
                    }
                }

                //职级
                if(ui->tableWidget_rm->item(rmCurrentRow,6)->text()!="")
                {
                    QString sqlRank = QString("select RankID from RankCode where RankName = '%1'").arg(ui->tableWidget_rm->item(rmCurrentRow,6)->text());
                    QSqlQuery queryRank;
                    queryRank.exec(sqlRank);
                    while(queryRank.next()) //一行一行遍历
                    {
                        rankId = queryRank.value(0).toString();
                    }
                }

                QSqlQuery query;
                QString sql = QString ("select PostID from Post where PostNumber = '%1'").arg(postNum);
                query.exec(sql);
                //任职文号或免职文号已存在
                if(query.next())
                {
                    QMessageBox::information(this,"提示信息","任免文号错误，请重新输入");
                }
                else//任免文号不存在，可插入记录
                {
                    QString sql = QString ("insert into Post values(null, '%1', '%2',null,null,'%3',null,'%4','%5','%6','%7')").arg(postName).arg(rankId).arg(postType).arg(postTime).arg(postNum).arg(idNum).arg(unitId);
                    if(query.exec(sql))
                    {
                        QMessageBox::information(this,"提示信息","插入成功");
                        //更新 现任职级
                        sql = QString ("update CadreInfo set RankID = '%1' where IDNum = '%2'").arg(rankId).arg(idNum);
                        query.exec(sql);
                        //任职->更新单位
                        if(postType == "0")
                        {
                            sql = QString ("update CadreInfo set UnitID = '%1' where IDNum = '%2'").arg(unitId).arg(idNum);
                            query.exec(sql);
                        }
    //                    else if(postType == "3")//免职更新（待定）
    //                    {
    //                        unitId = "null";
    //                        sql = QString ("update CadreInfo set UnitID = '%1' where IDNum = '%2'").arg(unitId).arg(idNum);
    //                        query.exec(sql);
    //                    }
                    }
                    else
                    {
                        //qDebug()<<postName<<rankId<<postType<<postTime<<postNum<<idNum<<unitId;
                        if(postTime == "null"){
                            QMessageBox::information(this, tr("提示"), tr("请输入任/免职时间！"), QMessageBox::tr("确定"));
                        }
                        if(unitId == "null"){
                            QMessageBox::information(this, tr("提示"), tr("请输入正确的单位名称！"), QMessageBox::tr("确定"));
                        }
                        if(postName == ""){
                            QMessageBox::information(this, tr("提示"), tr("请输入职务名称！"), QMessageBox::tr("确定"));
                        }
                        if(postNum == "null"){
                            QMessageBox::information(this, tr("提示"), tr("请输入任/免职文号！"), QMessageBox::tr("确定"));
                        }
                        if(rankId == "null"){
                            QMessageBox::information(this, tr("提示"), tr("请输入正确的职级名称！"), QMessageBox::tr("确定"));
                        }
                        //QMessageBox::information(this,"提示信息","信息不完善或不正确，请重试");
                    }
                }
            }
            else
            {
                if (ui->tableWidget_rm->rowCount() != 0)
                {
                    QMessageBox::critical(this, tr("错误！"), tr("未选中待插入记录！"));
                }
                else
                {
                    QMessageBox::critical(this, tr("错误！"), tr("表格中没有数据！"));
                }
            }
        }
        else if(result==QMessageBox::No)
        {
            return;
        }
    }
    else
    {
        QMessageBox::critical(this, tr("错误！"), tr("未选中干部记录！"));
    }
}

//添加记录行
void PostChange::on_buttonAdd_clicked()
{
    int rows = ui->tableWidget_rm->rowCount();
    int cols = ui->tableWidget_rm->columnCount();
    ui->tableWidget_rm->insertRow(rows);
    for(int i=0;i<cols;i++)
     ui->tableWidget_rm->setItem(rows,i,new QTableWidgetItem(""));
    ui->tableWidget_rm->selectRow(rows);
}

//删除记录行
void PostChange::on_buttonDel_clicked()
{
    int daCurrentRow = ui->tableWidget_da->currentRow();
    if (daCurrentRow != -1)//如果选中了数据，（未选择数据之前，返回值是-1）
    {
        int rmCurrentRow = ui->tableWidget_rm->currentRow();
        if (rmCurrentRow != -1)//如果选中了数据，（未选择数据之前，返回值是-1）
        {
            QMessageBox::StandardButton result;
            result = QMessageBox::question(this,"确认消息框","确认删除该条记录？",QMessageBox::Yes|QMessageBox::No);
            if(result==QMessageBox::Yes)
            {
                //删除数据库对应记录
                int daCurrentRow = ui->tableWidget_da->currentRow();
                QString idNum = ui->tableWidget_da->item(daCurrentRow, 1)->text();

                QSqlQuery query;
                QString sql;

                //有任职文号
                if(ui->tableWidget_rm->item(rmCurrentRow, 4)->text() != "" and ui->tableWidget_rm->item(rmCurrentRow, 5)->text() == "")
                {
                    sql = QString("delete from Post where QualifyType = '0' and IDNum = '%1' and PostNumber = '%2'").arg(idNum).arg(ui->tableWidget_rm->item(rmCurrentRow, 4)->text());
                }
                //有免职文号
                if(ui->tableWidget_rm->item(rmCurrentRow, 5)->text() != "" and ui->tableWidget_rm->item(rmCurrentRow, 4)->text() == "")
                {
                    sql = QString("delete from Post where QualifyType = '3' and IDNum = '%1' and PostNumber = '%2'").arg(idNum).arg(ui->tableWidget_rm->item(rmCurrentRow, 5)->text());
                }
                if(query.exec(sql)) QMessageBox::information(this,"提示信息","删除成功");

                QTableWidgetItem * item = ui->tableWidget_rm->currentItem();
                if(item == 0) return;
                ui->tableWidget_rm->removeRow(item->row());

            }
            else if(result==QMessageBox::No)
            {
                return;
            }
        }
        else
        {
            if (ui->tableWidget_rm->rowCount() != 0)
            {
                QMessageBox::critical(this, tr("错误！"), tr("未选择数据！"));
            }
            else
            {
                QMessageBox::critical(this, tr("错误！"), tr("表格中没有数据！"));
            }
        }
    }
    else
    {
         QMessageBox::critical(this, tr("错误！"), tr("未选中干部记录！"));
    }
}

void PostChange::on_buttonCM_clicked()
{
    emit postCMEdit();
}

//选择干部并显示对应干部的职务变动tableWidget//表任免记录（任职/免职）
void PostChange::on_tableWidget_da_itemSelectionChanged()
{
    ui->tableWidget_rm->setRowCount(0);
//    int currentRow = ui->tableWidget_da->currentRow();
//    if (currentRow != -1)//如果选中了一行
//    {
//        QString idNum = ui->tableWidget_da->item(currentRow,1)->text();
//        QSqlQuery query;
//        QString sqlP = QString("select RankID,QualifyType,PostTime,PostName,PostNumber,UnitID from Post where IDNum = '%1'").arg(idNum);
//        query.exec(sqlP);
//        while(query.next())
//        {
//            QString QualifyType = query.value(1).toString();
//            //任职or免职记录
//            if(QualifyType == "0"or QualifyType == "3")
//            {
//                int rows = ui->tableWidget_rm->rowCount();
//                ui->tableWidget_rm->insertRow(rows);
//                //任职时间/任职文号
//                if(QualifyType == "0")
//                {
//                    ui->tableWidget_rm->setItem(rows,0, new QTableWidgetItem(query.value(2).toString()));
//                    ui->tableWidget_rm->setItem(rows,1, new QTableWidgetItem(""));
//                    ui->tableWidget_rm->setItem(rows,4, new QTableWidgetItem(query.value(4).toString()));
//                    ui->tableWidget_rm->setItem(rows,5, new QTableWidgetItem(""));
//                }
//                //免职时间/免职文号
//                if(QualifyType == "3")
//                {
//                    ui->tableWidget_rm->setItem(rows,0, new QTableWidgetItem(""));
//                    ui->tableWidget_rm->setItem(rows,1, new QTableWidgetItem(query.value(2).toString()));
//                    ui->tableWidget_rm->setItem(rows,4, new QTableWidgetItem(""));
//                    ui->tableWidget_rm->setItem(rows,5, new QTableWidgetItem(query.value(4).toString()));
//                }
//                //职务
//                ui->tableWidget_rm->setItem(rows,3, new QTableWidgetItem(query.value(3).toString()));
//                //现任职级
//                QSqlQuery queryR;
//                QString sqlR = QString("select RankName from RankCode where RankID = '%1'").arg(query.value(0).toString());
//                queryR.exec(sqlR);
//                while(queryR.next())
//                {
//                    ui->tableWidget_rm->setItem(rows,6, new QTableWidgetItem(queryR.value(0).toString()));
//                }
//                //单位
//                QString sqlUnit = QString("select unitname from unit where unitid = '%1'").arg(query.value(5).toString());
//                QSqlQuery queryUnit;
//                queryUnit.exec(sqlUnit);
//                while(queryUnit.next()) //一行一行遍历
//                {
//                    ui->tableWidget_rm->setItem(rows,2,new QTableWidgetItem(queryUnit.value(0).toString()));
//                }
//            }
//        }
//    }
}

